Merge Sets and Convert to List in Java

  • Last updated Apr 25, 2024

In this tutorial, we will explore an example in Java that demonstrates how to merge the values of two sets and convert them into a list. Managing collections efficiently is crucial in many programming scenarios, and this tutorial provides a practical solution to this common task.

Here's an example that demonstrates how to merge the values of two sets and convert them into a list in Java:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class Example {

   public static void main(String[] args) {
      HashSet fruits = new HashSet<>();
      fruits.add("Grapes");
      fruits.add("Mango");
      fruits.add("Apple");
      fruits.add("Papaya");
      fruits.add("Pineapple");

      HashSet flowers = new HashSet<>();
      flowers.add("Tulip");
      flowers.add("Rose");
      flowers.add("Sunflower");
      flowers.add("Marigold");

      Map map = new HashMap<>();
      map.put("fruits", fruits);
      map.put("flowers", flowers);

      Set mergedSet = map.values().stream().flatMap(set -> ((Set) set).stream())
       .collect(Collectors.toSet());

      List list = new ArrayList<>(mergedSet);
      System.out.println(list);
   }

}

The output of the above code is as follows:

[Apple, Tulip, Grapes, Papaya, Mango, Rose, Pineapple, Sunflower, Marigold]